www.gusucode.com > 支持向量机工具箱 - LIBSVM OSU_SVM LS_SVM源码程序 > 支持向量机工具箱 - LIBSVM OSU_SVM LS_SVM\libsvm\demo3_2.m
% 一类支持向量机(OCSVM) - 已经调试通过 % DEMO3 One-Class Support Vector Classification with LIBSVM. % % The aim of a one-class SVM is to find the boundary of a data sample. % One-class SVMs are always nu style; this demo uses a SVM with Gauss % kernels. The solution can be illustrated as contour plot or as decision % function (dependent on the variable pps). % ------------------------------------------------------------------------------ % MATLAB Interface for LIBSVM, Version 1.2 % % Copyright (C) 2004-2005 Michael Vogt % Written by Michael Vogt, Atanas Ayarov and Bennet Gedan % % This program is free software; you can redistribute it and/or modify it % under the terms of the GNU General Public License as published by the Free % Software Foundation; either version 2 of the License, or (at your option) % any later version. % ------------------------------------------------------------------------------ clc clear %close all % ------------------------------------------------------------% % 定义核函数及相关参数 nu = 0.2; % nu -> [0,1] 在支持向量数与错分样本数之间进行折衷 % 支持向量机的 nu 参数(取值越小,异常点就越少) %ker = struct('type','linear'); %ker = struct('type','ploy','degree',3,'offset',1); ker = struct('type','gauss','width',500); %ker = struct('type','tanh','gamma',1,'offset',0); % ker - 核参数(结构体变量) % the following fields: % type - linear : k(x,y) = x'*y % poly : k(x,y) = (x'*y+c)^d % gauss : k(x,y) = exp(-0.5*(norm(x-y)/s)^2) % tanh : k(x,y) = tanh(g*x'*y+c) % degree - Degree d of polynomial kernel (positive scalar). % offset - Offset c of polynomial and tanh kernel (scalar, negative for tanh). % width - Width s of Gauss kernel (positive scalar). % gamma - Slope g of the tanh kernel (positive scalar). % ------------------------------------------------------------% % 构造一类训练样本 n = 100 randn('state',1); x1 = randn(floor(n*0.95),2); x2 = 5+randn(ceil(n*0.05),2); X = [x1;x2]; % 训练样本,n×d的矩阵,n为样本个数,d为样本维数 figure; plot(x1(:,1),x1(:,2),'bx',x2(:,1),x2(:,2),'k.'); axis([-5 8 -5 8]); title('One-Class SVM'); hold on; % ------------------------------------------------------------% % 训练支持向量机 tic svm = libsvmopt(X,[],nu,ker) t_train = toc % svm 支持向量机(结构体变量) % the following fields: % ker - 核参数 % x - 训练样本 % y - 训练目标; % a - 拉格朗日乘子 % ------------------------------------------------------------% % 寻找支持向量 vect = svm.vect; plot(vect(:,1),vect(:,2),'ro'); % ------------------------------------------------------------% % 测试输出 [x1,x2] = meshgrid(-4:0.05:6,-4:0.05:6); [rows,cols] = size(x1); nt = rows*cols; % 测试样本数 Xt = [reshape(x1,nt,1),reshape(x2,nt,1)]; tic Yd = libsvmsim(svm,Xt); % 测试输出 t_sim = toc Yd = reshape(Yd,rows,cols); contour(x1,x2,Yd,[0 0],'m'); % 分类面 hold off;